/**
 * Hello World 演示工具
 * 展示如何创建新的工具模块，包含基础表单功能
 */

const FileHelper = require('../utils/file-helper');
const Logger = require('../utils/logger');

class HelloWorldTool {
    constructor() {
        // DOM元素引用
        this.elements = this.getElements();
        
        // 初始化工具类
        this.logger = new Logger('logContainer');
        
        this.init();
    }

    /**
     * 获取DOM元素引用
     * @returns {Object} DOM元素对象
     */
    getElements() {
        return {
            demoText: document.getElementById('demoText'),
            demoNumber: document.getElementById('demoNumber'),
            demoSelect: document.getElementById('demoSelect'),
            demoTextarea: document.getElementById('demoTextarea'),
            demoCheck1: document.getElementById('demoCheck1'),
            demoCheck2: document.getElementById('demoCheck2'),
            demoCheck3: document.getElementById('demoCheck3'),
            demoSubmit: document.getElementById('demoSubmit'),
            demoClear: document.getElementById('demoClear'),
            demoExport: document.getElementById('demoExport'),
            demoResult: document.getElementById('demoResult')
        };
    }

    /**
     * 初始化工具
     */
    init() {
        this.bindEvents();
        this.logger.info('示例工具演示模块已初始化');
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        const { elements } = this;

        // 按钮事件
        elements.demoSubmit?.addEventListener('click', () => this.handleSubmit());
        elements.demoClear?.addEventListener('click', () => this.handleClear());
        elements.demoExport?.addEventListener('click', () => this.handleExport());

        // 表单变化事件（可选）
        this.bindFormChangeEvents();
    }

    /**
     * 绑定表单变化事件
     */
    bindFormChangeEvents() {
        const { elements } = this;

        // 文本输入实时验证
        elements.demoText?.addEventListener('input', (e) => {
            this.validateTextInput(e.target.value);
        });

        // 数字输入验证
        elements.demoNumber?.addEventListener('input', (e) => {
            this.validateNumberInput(e.target.value);
        });

        // 选择框变化
        elements.demoSelect?.addEventListener('change', (e) => {
            this.onSelectChange(e.target.value);
        });
    }

    /**
     * 处理提交数据
     */
    handleSubmit() {
        try {
            const formData = this.collectFormData();
            const validationResult = this.validateFormData(formData);

            if (!validationResult.isValid) {
                this.showValidationErrors(validationResult.errors);
                return;
            }

            this.displaySubmitResult(formData);
            this.logger.success('表单数据提交成功');
        } catch (error) {
            this.logger.error(`提交失败: ${error.message}`);
        }
    }

    /**
     * 收集表单数据
     * @returns {Object} 表单数据对象
     */
    collectFormData() {
        const { elements } = this;

        return {
            text: elements.demoText?.value || '',
            number: elements.demoNumber?.value || '',
            select: elements.demoSelect?.value || '',
            textarea: elements.demoTextarea?.value || '',
            checkboxes: {
                check1: elements.demoCheck1?.checked || false,
                check2: elements.demoCheck2?.checked || false,
                check3: elements.demoCheck3?.checked || false
            },
            radio: this.getSelectedRadioValue(),
            timestamp: new Date().toISOString()
        };
    }

    /**
     * 获取选中的单选框值
     * @returns {string} 单选框值
     */
    getSelectedRadioValue() {
        const selectedRadio = document.querySelector('input[name="demoRadio"]:checked');
        return selectedRadio ? selectedRadio.value : '';
    }

    /**
     * 验证表单数据
     * @param {Object} formData - 表单数据
     * @returns {Object} 验证结果
     */
    validateFormData(formData) {
        const errors = [];

        // 文本输入验证
        if (!formData.text.trim()) {
            errors.push('文本输入不能为空');
        } else if (formData.text.length > 100) {
            errors.push('文本输入不能超过100个字符');
        }

        // 数字输入验证
        if (formData.number && (isNaN(formData.number) || formData.number < 0 || formData.number > 100)) {
            errors.push('数字输入必须在0-100之间');
        }

        // 选择框验证
        if (!formData.select) {
            errors.push('请选择一个选项');
        }

        return {
            isValid: errors.length === 0,
            errors: errors
        };
    }

    /**
     * 显示验证错误
     * @param {Array} errors - 错误数组
     */
    showValidationErrors(errors) {
        const errorHtml = `
            <div style="color: #e74c3c; background: #fdf2f2; padding: 15px; border-radius: 6px; margin-top: 10px;">
                <h4>表单验证失败：</h4>
                <ul style="margin: 10px 0 0 20px;">
                    ${errors.map(error => `<li>${error}</li>`).join('')}
                </ul>
            </div>
        `;
        
        this.elements.demoResult.innerHTML = errorHtml;
        this.logger.warning(`表单验证失败: ${errors.join(', ')}`);
    }

    /**
     * 显示提交结果
     * @param {Object} formData - 表单数据
     */
    displaySubmitResult(formData) {
        const checkedOptions = Object.entries(formData.checkboxes)
            .filter(([key, value]) => value)
            .map(([key, value]) => key.replace('check', '选项'))
            .join(', ') || '(未选择)';

        const resultHtml = `
            <div style="background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 6px; padding: 15px; margin-top: 10px;">
                <h4 style="color: #0c4a6e; margin-bottom: 15px;">✅ 提交成功！</h4>
                <div style="background: white; padding: 15px; border-radius: 6px;">
                    <p><strong>文本输入:</strong> ${formData.text || '(空)'}</p>
                    <p><strong>数字输入:</strong> ${formData.number || '(空)'}</p>
                    <p><strong>选择框:</strong> ${formData.select || '(未选择)'}</p>
                    <p><strong>多行文本:</strong> ${formData.textarea || '(空)'}</p>
                    <p><strong>复选框:</strong> ${checkedOptions}</p>
                    <p><strong>单选框:</strong> ${formData.radio || '(未选择)'}</p>
                    <p><strong>提交时间:</strong> ${new Date(formData.timestamp).toLocaleString()}</p>
                </div>
            </div>
        `;
        
        this.elements.demoResult.innerHTML = resultHtml;
    }

    /**
     * 处理清空表单
     */
    handleClear() {
        try {
            this.clearAllFormFields();
            this.showClearResult();
            this.logger.info('表单已清空');
        } catch (error) {
            this.logger.error(`清空表单失败: ${error.message}`);
        }
    }

    /**
     * 清空所有表单字段
     */
    clearAllFormFields() {
        const { elements } = this;

        // 清空文本输入
        if (elements.demoText) elements.demoText.value = '';
        if (elements.demoNumber) elements.demoNumber.value = '';
        if (elements.demoSelect) elements.demoSelect.value = '';
        if (elements.demoTextarea) elements.demoTextarea.value = '';

        // 清空复选框
        if (elements.demoCheck1) elements.demoCheck1.checked = false;
        if (elements.demoCheck2) elements.demoCheck2.checked = false;
        if (elements.demoCheck3) elements.demoCheck3.checked = false;

        // 清空单选框
        document.querySelectorAll('input[name="demoRadio"]').forEach(radio => {
            radio.checked = false;
        });
    }

    /**
     * 显示清空结果
     */
    showClearResult() {
        const resultHtml = `
            <div style="background: #f0fdf4; border: 1px solid #22c55e; border-radius: 6px; padding: 15px; margin-top: 10px;">
                <p style="color: #15803d; margin: 0;">🧹 表单已清空</p>
            </div>
        `;
        
        this.elements.demoResult.innerHTML = resultHtml;
    }

    /**
     * 处理导出数据
     */
    handleExport() {
        try {
            const formData = this.collectFormData();
            const exportData = this.prepareExportData(formData);
            
            FileHelper.exportJSON(exportData, 'hello-world-data');
            
            this.showExportResult();
            this.logger.success('数据已导出为JSON文件');
        } catch (error) {
            this.logger.error(`导出失败: ${error.message}`);
        }
    }

    /**
     * 准备导出数据
     * @param {Object} formData - 表单数据
     * @returns {Object} 导出数据
     */
    prepareExportData(formData) {
        return {
            ...formData,
            metadata: {
                tool: 'Hello World Demo',
                version: '2.0.0',
                exportTime: new Date().toISOString(),
                userAgent: navigator.userAgent
            },
            statistics: {
                textLength: formData.text.length,
                textareaLength: formData.textarea.length,
                checkedCount: Object.values(formData.checkboxes).filter(Boolean).length,
                hasRadioSelection: !!formData.radio,
                hasSelectSelection: !!formData.select
            }
        };
    }

    /**
     * 显示导出结果
     */
    showExportResult() {
        const resultHtml = `
            <div style="background: #f0f9ff; border: 1px solid #3b82f6; border-radius: 6px; padding: 15px; margin-top: 10px;">
                <p style="color: #1d4ed8; margin: 0;">📁 数据已导出为JSON文件</p>
                <small style="color: #64748b;">文件已保存到下载目录</small>
            </div>
        `;
        
        this.elements.demoResult.innerHTML = resultHtml;
    }

    /**
     * 文本输入验证
     * @param {string} value - 输入值
     */
    validateTextInput(value) {
        // 实时验证逻辑（可选）
        if (value.length > 100) {
            this.logger.warning('文本输入超过100个字符');
        }
    }

    /**
     * 数字输入验证
     * @param {string} value - 输入值
     */
    validateNumberInput(value) {
        // 实时验证逻辑（可选）
        const num = parseFloat(value);
        if (value && (isNaN(num) || num < 0 || num > 100)) {
            this.logger.warning('数字输入应在0-100之间');
        }
    }

    /**
     * 选择框变化处理
     * @param {string} value - 选择值
     */
    onSelectChange(value) {
        if (value) {
            this.logger.info(`已选择选项: ${value}`);
        }
    }

    /**
     * 获取工具状态
     * @returns {Object} 工具状态
     */
    getToolStatus() {
        const formData = this.collectFormData();
        
        return {
            hasData: Object.values(formData).some(value => 
                typeof value === 'string' ? value.trim() !== '' : 
                typeof value === 'object' ? Object.values(value).some(Boolean) : 
                Boolean(value)
            ),
            formData: formData,
            lastUpdate: new Date().toISOString()
        };
    }

    /**
     * 重置工具状态
     */
    reset() {
        this.handleClear();
        this.logger.info('示例工具已重置');
    }
}

module.exports = HelloWorldTool;